package com.askinhand.service.impl;

import java.util.ArrayList;
import java.util.List;

import java.util.Iterator;

import com.askinhand.bean.User;
import com.askinhand.bean.UserInfo;
import com.askinhand.dao.IUserDAO;
import com.askinhand.dao.IUserInfoDAO;
import com.askinhand.service.IUserService;

public class UserService implements IUserService {
	IUserDAO userDAO;

	IUserInfoDAO userInfoDAO;

	public IUserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(IUserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public IUserInfoDAO getUserInfoDAO() {
		return userInfoDAO;
	}

	public void setUserInfoDAO(IUserInfoDAO userInfoDAO) {
		this.userInfoDAO = userInfoDAO;
	}

	public String login(User user) {
		List li = userDAO.findByUsername(user.getUsername());
		if (li.size() > 0) {
			Iterator it = li.iterator();
			while (it.hasNext()) {
				User u = (User) (it.next());
				if (u.getType().equals(user.getType())
						&& u.getPassword().equals(user.getPassword())) {
					return u.getId()+"";
				}
			}
			return "fail";
		} else {
			return "notexist";
		}
	}

	public String register(User user, UserInfo userinfo) {
		
		List list=userDAO.findByUsername(user.getUsername());
		if(list.size()!=0)
			return "fail";
		else
			userDAO.save(user);
		
		int id=0;
		
		list=userDAO.findByUsername(user.getUsername());
		id=((User) list.get(0)).getId();
		
		userinfo.getUser().setId(id);
		
		
		userInfoDAO.save(userinfo);
		
		return "success";
	}

	public UserInfo userInfoRetrieve(String uid) {
		
		List list=userInfoDAO.findByUid(Integer.parseInt(uid));
		
		if(list.size()!=0)
			return (UserInfo)list.get(0);
		return new UserInfo();
	}

	/**
	 * �û��޸ĸ�����Ϣʱʹ��
	 */
	public String userInfoSave(UserInfo userinfo) {
		
		System.out.println("UserService.userInfoSave() userinfo="+userinfo);

		List userInfoList = userInfoDAO.findByUid(userinfo.getUser().getId());
		
		if(userInfoList!=null && userInfoList.size()!=0) {
			UserInfo current=(UserInfo)userInfoList.get(0);
			userInfoDAO.delete(current);
			userinfo.setSpoints(current.getSpoints());
			userinfo.setPpoints(current.getPpoints());
			userinfo.setTitle(current.getTitle());
		}else {
			userinfo.setSpoints(0);
			userinfo.setPpoints(0);
		}
		System.out.println("UserService.userInfoSave() name="+userinfo.getName());
		userInfoDAO.save(userinfo);
		return "success";
	}

	public String changePassword(String password, String uid) {
		
		User user=userDAO.findById(Integer.parseInt(uid));
		user.setPassword(password);
		userDAO.merge(user);
		return "success";
	}

	public List getPoints(String uid) {
		UserInfo userinfo=(UserInfo)userInfoDAO.findByUid(Integer.parseInt(uid));
		int ppoints=userinfo.getPpoints();
		int spoints=userinfo.getSpoints();
		List list=new ArrayList<Integer>();
		list.add(ppoints);
		list.add(spoints);
		
		
		
		return list;
	}
}
